package au.com.betaversion;

import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import au.com.betaversion.domain.Airport;
import au.com.betaversion.repository.AirportRepository;

@Controller
@RequestMapping("/airport")
public class AirportController {
	
	@Autowired
	private AirportRepository airportRepository;
	
	@ModelAttribute("airportModel")
	public Airport airportModel() {
		return new Airport();
	}
	
	@RequestMapping(method = RequestMethod.GET)
	public String aiportDefault(Model model) {
		List<Airport> airports = airportRepository.findAll();
		
		Collections.sort(airports);
		
		model.addAttribute("airports", airports);
		return "airport";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String aiportPost(@ModelAttribute("airportModel") Airport airport, 
			RedirectAttributes redirectAttributes) {
		airportRepository.save(airport);
		redirectAttributes.addFlashAttribute("message", "'" + airport.getName() + "' airpot added");
		return "redirect:/airport";
	}

}
